import { _decorator, Component, Node, resources, Sprite, SpriteFrame, tween, Vec3 } from 'cc';
import { BallColor } from './Enums';
import { Tube } from './Tube';
const { ccclass, property } = _decorator;

@ccclass('Ball')
export class Ball extends Component {
    @property({
        type: BallColor,
        tooltip: '球的颜色'
    })
    ballColor: BallColor = BallColor.RED;

    @property(Node)
    node: Node = null; // 小球节点
    @property(Node)
    effectNode: Node = null; // 特效节点

    public tube: Tube;        // 所在试管
    //public posInTube: number;        // 在试管里的位置（0=最底部）

    // 资源路径映射
    private static readonly COLOR_FRAME_MAP: Record<BallColor, string> = {
        [BallColor.RED]: 'Balls/1',
        [BallColor.YELLOW]: 'Balls/2',
        [BallColor.ORANGE]: 'Balls/3',
        [BallColor.BLUE]: 'Balls/4',
        [BallColor.LIGHT_GREEN]: 'Balls/5',
        [BallColor.GREEN]: 'Balls/6',
        [BallColor.PURPLE]: 'Balls/7',
        [BallColor.SKY_BLUE]: 'Balls/8',
        [BallColor.MAGENTA]: 'Balls/9',
        [BallColor.PINK]: 'Balls/10',
        [BallColor.AZURE]: 'Balls/11',
        [BallColor.BROWN]: 'Balls/12',
    };

    start() {
        this.loadSpriteFrame();
    }

    update(deltaTime: number) {
        
    }

    // 加载球的贴图
    private loadSpriteFrame() {
        const path = Ball.COLOR_FRAME_MAP[this.ballColor]+'/spriteFrame';
        if (!path) {
            console.error(`未找到颜色 ${this.ballColor} 的贴图路径`);
            return;
        }

        console.log(`尝试加载路径: ${path}`);
        resources.load(path, SpriteFrame, (err, spriteFrame) => {
            if (err) {
                console.error(`加载球贴图失败: ${err}`);
                return;
            }
            //console.log(`加载成功，设置 SpriteFrame`);
            const sprite = this.getComponent(Sprite);
            if (sprite) {
                sprite.spriteFrame = spriteFrame;
                //console.log(`SpriteFrame 设置成功`);
            } else {
                console.error(`未找到 Sprite 组件`);
            }
        });
    }

    /**
     * 移动到指定位置（如试管顶部），仅缓动，动画结束后调用回调
     */
    moveTo(pos: Vec3, duration: number = 0.3, onComplete?: () => void) {
        tween(this.node)
            .to(duration, { position: pos }, { easing: 'quadInOut' })
            .call(() => {
                if (onComplete) onComplete();
            })
            .start();
    }

    /**
     * 移动到目标点后弹跳两次，第一次弹跳高度 30，第二次 10，动画结束后调用回调
     * @param pos 目标位置
     * @param duration 移动到目标位置的时长
     * @param onComplete 动画完成回调
     */
    moveToWithBounce(pos: Vec3, duration: number = 0.3, onComplete?: () => void) {
        const firstBounceHeight = 30;
        const secondBounceHeight = 10;

        tween(this.node)
            .to(duration, { position: pos }, { easing: 'quadInOut' })
            // 第一次弹跳
            .to(0.15, { position: new Vec3(pos.x, pos.y + firstBounceHeight, pos.z) }, { easing: 'quadOut' })
            .to(0.15, { position: pos }, { easing: 'quadIn' })
            // 第二次弹跳
            .to(0.1, { position: new Vec3(pos.x, pos.y + secondBounceHeight, pos.z) }, { easing: 'quadOut' })
            .to(0.1, { position: pos }, { easing: 'quadIn' })
            .call(() => {
                if (onComplete) onComplete();
            })
            .start();
    }

    /**
     * 先移动到试管顶部，再移动到目标点并弹跳，动画结束后调用回调
     */
    moveToOtherTube(topPos: Vec3, targetPos: Vec3, bounceHeight: number = 30, duration: number = 0.3, onComplete?: () => void) {
        tween(this.node)
            .to(duration, { position: topPos }, { easing: 'quadInOut' })
            .to(duration, { position: targetPos }, { easing: 'quadInOut' })
            .to(0.1, { position: targetPos.add(new Vec3(0, bounceHeight, 0)) }, { easing: 'quadOut' })
            .to(0.1, { position: targetPos }, { easing: 'quadIn' })
            .to(0.08, { position: targetPos.add(new Vec3(0, bounceHeight * 0.5, 0)) }, { easing: 'quadOut' })
            .to(0.08, { position: targetPos }, { easing: 'quadIn' })
            .call(() => {
                if (onComplete) onComplete();
            })
            .start();
    }

    // 显示选中特效
    showEffect() {
        if (this.effectNode) this.effectNode.active = true;
    }

    // 隐藏选中特效
    hideEffect() {
        if (this.effectNode) this.effectNode.active = false;
    }
}